#include "System.h"

System::System()
{
	window = new sf::RenderWindow(sf::VideoMode(1280, 720), "Title", 3, sf::ContextSettings(0, 0, 4, 2, 0));

	worldPhysics = new PhysicsManager;
	worldPhysics->setupWorld(b2Vec2(0.0f, -0.098));
	
	worldObjects = new ObjectManager(worldPhysics->getGameWorld());
	input = new UserInput;
	drawer = new Drawer;

	isDebugging = false;
}

System::~System()
{
	if(window) delete window;
	if(worldPhysics) delete worldPhysics;
	if(worldObjects) delete worldObjects;
	if(input) delete input;
	if(drawer) delete drawer;
}


void System::runLoop()
{
	initScene();

	while(window->isOpen())
	{
		setFramePreconditions();

		while(window->pollEvent(event))
	    {
		    if(event.type == sf::Event::Closed)
			    window->close();
	    }

		checkInput();
	
		updateScene();
		drawScene();
	}
}

////////////////////PRIVATE METHODS///////////////////////////

void System::initScene()
{
	worldObjects->addGround(-705.0f, 1280.0f);
	debugHelper.init();
}

void System::checkInput()
{
	input->addItemsToScene(worldObjects, time.asSeconds(), window);
}

void System::setFramePreconditions()
{
	time = clock.getElapsedTime();

	input->initFrameInput(time.asSeconds());
}


void System::updateScene()
{
	worldPhysics->updateGameWorld(worldObjects->getActiveRectList(), worldObjects->getActiveCircleList(), 1.0f / 6.0f);
}

void System::drawScene()
{

	window->clear();
	drawer->drawGround(worldObjects->getGround(), window);
	drawer->drawActiveObjects(worldObjects->getActiveRectList(), worldObjects->getActiveCircleList(), window);
	window->display();
}